package com.school.service;

import com.school.common.PageRequest;
import com.school.common.PageResult;
import com.school.common.ResultCode;
import com.school.dao.StudentDao;
import com.school.dao.mybatis.StudentMapper;
import com.school.entity.Student;
import com.school.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 学生服务类
 */
@Slf4j
@Service
public class StudentService {
    
    @Autowired
    private StudentDao studentDao;
    
    @Autowired
    private StudentMapper studentMapper;
    
    @Autowired
    private ClassService classService;
    
    /**
     * 添加学生
     */
    @Transactional(rollbackFor = Exception.class)
    public Long add(Student student) {
        // 验证学号是否已存在
        Student existStudent = studentDao.findByStudentId(student.getStudentId());
        if (existStudent != null) {
            throw new BusinessException(ResultCode.STUDENT_ID_EXISTED);
        }
        
        // 验证班级是否存在，并自动填充班主任和专业
        if (!StringUtils.isEmpty(student.getClassName())) {
            com.school.entity.Class clazz = classService.getByClassName(student.getClassName());
            if (clazz != null) {
                student.setTeacherName(clazz.getTeacherName());
                student.setMajor(clazz.getMajor());
            }
        }
        
        return studentDao.insert(student);
    }
    
    /**
     * 更新学生
     */
    @Transactional(rollbackFor = Exception.class)
    public void update(Student student) {
        Student existStudent = studentDao.findById(student.getId());
        if (existStudent == null) {
            throw new BusinessException(ResultCode.STUDENT_NOT_EXIST);
        }
        
        // 验证班级是否存在，并自动填充班主任和专业
        if (!StringUtils.isEmpty(student.getClassName())) {
            com.school.entity.Class clazz = classService.getByClassName(student.getClassName());
            if (clazz != null) {
                student.setTeacherName(clazz.getTeacherName());
                student.setMajor(clazz.getMajor());
            }
        }
        
        studentDao.update(student);
    }
    
    /**
     * 删除学生
     */
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        Student existStudent = studentDao.findById(id);
        if (existStudent == null) {
            throw new BusinessException(ResultCode.STUDENT_NOT_EXIST);
        }
        
        studentDao.deleteById(id);
    }
    
    /**
     * 批量删除学生
     */
    @Transactional(rollbackFor = Exception.class)
    public int batchDelete(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            throw new BusinessException("删除ID列表不能为空");
        }
        
        log.info("批量删除学生，数量: {}", ids.size());
        return studentDao.batchDelete(ids);
    }
    
    /**
     * 根据ID查询学生
     */
    public Student getById(Long id) {
        Student student = studentDao.findById(id);
        if (student == null) {
            throw new BusinessException(ResultCode.STUDENT_NOT_EXIST);
        }
        return student;
    }
    
    /**
     * 根据学号查询学生
     */
    public Student getByStudentId(String studentId) {
        return studentDao.findByStudentId(studentId);
    }
    
    /**
     * 分页查询学生列表
     */
    public PageResult<Student> getPageList(String studentId, String name, String className, 
                                           String building, String status, PageRequest pageRequest) {
        Map<String, Object> params = new HashMap<>();
        params.put("studentId", studentId);
        params.put("name", name);
        params.put("className", className);
        params.put("building", building);
        params.put("status", status);
        params.put("offset", pageRequest.getOffset());
        params.put("limit", pageRequest.getLimit());
        
        List<Student> list = studentDao.findByPage(params);
        long total = studentDao.count(params);
        
        return PageResult.of(pageRequest.getPageNum(), pageRequest.getPageSize(), total, list);
    }
    
    /**
     * 批量导入学生
     */
    @Transactional(rollbackFor = Exception.class)
    public int batchImport(List<Student> students) {
        if (students == null || students.isEmpty()) {
            throw new BusinessException("导入数据不能为空");
        }
        
        // 验证数据
        for (Student student : students) {
            // 检查学号是否重复
            Student existStudent = studentDao.findByStudentId(student.getStudentId());
            if (existStudent != null) {
                throw new BusinessException("学号已存在: " + student.getStudentId());
            }
            
            // 自动填充班主任和专业
            if (!StringUtils.isEmpty(student.getClassName())) {
                com.school.entity.Class clazz = classService.getByClassName(student.getClassName());
                if (clazz != null) {
                    student.setTeacherName(clazz.getTeacherName());
                    student.setMajor(clazz.getMajor());
                }
            }
        }
        
        return studentDao.batchInsert(students);
    }
    
    /**
     * 查询所有学生（用于导出）
     */
    public List<Student> getAllStudents() {
        return studentMapper.findAll();
    }
}


